﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Configuration;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using ScrumFactory.Services;
using System.Deployment.Application;

namespace ScrumFactory.Services.Clients {

    public class ServiceClient {

        private static System.Net.Http.HttpClientHandler httpHandle;

        public static string ClientVersion {
            get {
                string version = "DEV";                
                if (ApplicationDeployment.IsNetworkDeployed)
                    version = ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
                return version;
            }
        }

        public static string UserAgent {
            get {
                return "SFClient-" + ClientVersion;
            }
        }

        public static System.Net.Http.HttpClient GetClient() {
            return GetClient(null);
        }

        public static System.Net.Http.HttpClient GetClient(IAuthorizationService authService) {
            ConfigureHttpHandle();

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(httpHandle);

            if (authService != null) {
                if (authService.SignedMemberProfile == null)
                    throw new ScrumFactory.Exceptions.NotAuthorizedException();

                client.DefaultRequestHeaders.AddWithoutValidation("Authorization", authService.SignedMemberProfile.AuthorizationProvider + " auth=" + authService.SignedMemberToken);
            }

            // user agent
            client.DefaultRequestHeaders.Add("UserAgent", UserAgent);

            // max response buffer
            client.MaxResponseContentBufferSize = 1024 * 1024 * 10;

            return client;

        }


        public static void HandleHTTPErrorCode(System.Net.Http.HttpResponseMessage response) {

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return;

            if (response.StatusCode == System.Net.HttpStatusCode.HttpVersionNotSupported) {
                string content = response.Content.ReadAsString().Replace("\"", "");
                throw new ScrumFactory.Exceptions.VersionMissmatchException(content, ClientVersion);
            }

            if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) {
                string content = response.Content.ReadAsString().Replace("\"", "");
                if (content.StartsWith("BRE_"))
                    throw new ScrumFactory.Exceptions.BusinessRuleViolationException(content);
            }

            if (response.StatusCode == System.Net.HttpStatusCode.NotFound) {
                throw new ScrumFactory.Exceptions.NotFoundException();
            }

            if (response.StatusCode == System.Net.HttpStatusCode.Forbidden) {
                throw new ScrumFactory.Exceptions.ForbittenException();
            }

            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) {
                throw new ScrumFactory.Exceptions.NotAuthorizedException();
            }

            if (response.StatusCode == System.Net.HttpStatusCode.BadGateway
                || response.StatusCode == System.Net.HttpStatusCode.GatewayTimeout) {
                throw new ScrumFactory.Exceptions.NetworkException();
            }


            throw new Exceptions.ServerErrorException();
        }


        public static void ConfigureHttpHandle() {

            if (httpHandle != null)
                return;

            // create handle
            httpHandle = new System.Net.Http.HttpClientHandler();
            
            // configure proxy
            httpHandle.Proxy = GetProxy();

            // max request buffer
            httpHandle.MaxRequestContentBufferSize = 1024 * 1024 * 10;
            

        }

        public static System.Net.IWebProxy GetProxy() {

            return System.Net.WebRequest.DefaultWebProxy;

            //System.Net.IWebProxy proxy = null;

            //// configure proxy
            //Microsoft.Win32.RegistryKey internetSettingsKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings");
            //int? proxyEnable = internetSettingsKey.GetValue("ProxyEnable") as int?;
            //string proxyServer = internetSettingsKey.GetValue("ProxyServer") as string;
            //string proxyOverride = internetSettingsKey.GetValue("ProxyOverride") as string;
            //bool byPassLocal = "<local>".Equals(proxyOverride);

            //if (proxyEnable.HasValue && proxyEnable.Value == 1)
            //    proxy = new System.Net.WebProxy(proxyServer, byPassLocal, null, System.Net.CredentialCache.DefaultCredentials);

            //return proxy;
        }

       

    }
}
